<?php
class IOSS_PaymentConfig {
	const STATUS_ENABLE = 1;
	const STATUS_DISABLE = 0;
	
	private static $table = 'core_payment_config';
	private static $instances_all;
	private static $instances_id;
	private static $instances_code;
	
	
	public $id;
	public $code;
	public $gateway;
	public $view;
	public $name;
	public $description;
	public $sort;
	public $configs;
	public $imgname;
	
	
	private function __construct($vo){
		$this->id = $vo->id;
		$this->code = $vo->code;
		$this->gateway = $vo->gateway;
		$this->view = $vo->view;
		$this->name = $vo->name;
		$this->description = $vo->description;
		$this->sort = (int)$vo->sort;
		$this->configs = $vo->configs;
		$codeArr = explode('_', $vo->code);
		$this->imgname = $codeArr[1];
		/*
		foreach (explode("\r\n", $vo->configs) as $line){
			if(strpos($line, '=') > 0){
				list($k, $v) = explode('=', $line, 2);
				$this->configs[trim($k)] = trim($v);
			}
		}*/
	}
	

	/**
	 * @param int $id
	 * @return NULL|IOSS_PaymentConfig
	 */
	public static function getById($id){
		if(!isset(self::$instances_id) || !array_key_exists($id, self::$instances_id)){
			$db = IOSS_DB::getInstance();
			$row = $db->get_where(self::$table, array('id' => $id, 'status'=>self::STATUS_ENABLE))->row();
			self::$instances_id[$id] = $row ? (new self($row)) : null;
		}
		return self::$instances_id[$id];
	}
	
	/**
	 * @param string $code
	 * @return NULL|IOSS_PaymentConfig
	 */
	public static function getByCode($code){
		if(!isset(self::$instances_code) || !array_key_exists($code, self::$instances_code)){
			$db = IOSS_DB::getInstance();
			$row = $db->get_where(self::$table, array('code' => $code, 'status'=>self::STATUS_ENABLE))->row();
			self::$instances_code[$code] = $row ? (new self($row)) : null;
		}
		return self::$instances_code[$code];
	}
	
	/**
	 * @param int $user_id
	 * @return array<IOSS_PaymentConfig>
	 */
	public static function getAll(){
		if(self::$instances_all === null){
			self::$instances_all = array();
			$db = IOSS_DB::getInstance();
			$db->order_by('sort', 'ASC');
			$db->where('status', self::STATUS_ENABLE);
			$rows = $db->get(self::$table)->result();
			foreach ($rows as $row){
				self::$instances_all[] = new self($row);
			}
		}
		return self::$instances_all;
	}
}